﻿#include "CapitalDataAddDlg.h"
#include "ui_CapitalDataAddDlg.h"
#include <QUuid>
#include "DBManage.h"

CapitalDataAddDlg::CapitalDataAddDlg(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CapitalDataAddDlg)
{
    ui->setupUi(this);
    this->setAttribute(Qt::WA_ShowModal, true);

    ui->spinBox_startTime->setRange(-9999, 9999);
    ui->spinBox_endTime->setRange(-9999, 9999);

    m_capitalID = "";
    m_isModify = false;

    connect(ui->pushButton_save, SIGNAL(clicked()), this, SLOT(slotSaveCountryData()));
    connect(ui->pushButton_cancel, SIGNAL(clicked()), this, SLOT(close()));
    ui->comboBox->setEnabled(true);
}

CapitalDataAddDlg::~CapitalDataAddDlg()
{
    delete ui;
}

void CapitalDataAddDlg::clearContents()
{
    m_isModify = false;
    ui->spinBox_startTime->setValue(0);
    ui->spinBox_endTime->setValue(0);
    ui->lineEdit_name->clear();
    updateCountryItems();

    m_capitalID = QUuid::createUuid().toString();
    ui->lineEdit_capitalID->setText(m_capitalID);
}

void CapitalDataAddDlg::setData(const Capital &data)
{
    m_isModify = true;
    m_capitalID = true;
    updateCountryItems();

    ui->spinBox_startTime->setValue(data.startTime);
    ui->spinBox_endTime->setValue(data.endTime);
    ui->lineEdit_name->setText(data.capitalName);
    int currentIndex = ui->comboBox->findData(data.countryID);  // 按照countryID找是哪个政权
    ui->comboBox->setCurrentIndex(currentIndex);

    m_capitalID = data.capitalID;
    ui->lineEdit_capitalID->setText(m_capitalID);
}

void CapitalDataAddDlg::slotSaveCountryData()
{
    Capital data;
    data.startTime = ui->spinBox_startTime->value();
    data.endTime = ui->spinBox_endTime->value();
    data.capitalName = ui->lineEdit_name->text();
    QString countryID = ui->comboBox->currentData().toString();
    data.countryID = countryID;
    data.capitalID = m_capitalID;

    emit sigCapitalData(data, m_isModify);
    this->close();
}

void CapitalDataAddDlg::updateCountryItems()
{
    ui->comboBox->blockSignals(true);
    ui->comboBox->clear();
    m_lstCountry.clear();

    m_lstCountry = DBManage::getInstance()->getCountryDatas();
    for(int i = 0;  i < m_lstCountry.size(); ++i)
    {
        ui->comboBox->addItem(m_lstCountry[i].countryName, m_lstCountry[i].countryID);
    }
    ui->comboBox->setCurrentIndex(-1);
    ui->comboBox->blockSignals(false);
}
